local mForce = {
    type = 'module',
    module = 'force',
    ---@type player[]
    regList = {},
}
---@class cForce
local cForce = {
    type = 'class',
    class = 'force',

}
cForce.__index = cForce

local setmetatable = setmetatable
local table_insert = table_insert
local table = table

---注册玩家组模块
local onReg = function ()
    for i = 1, 16 do
        mForce:reg( player[i] )
    end
end

---@private 注册进玩家组模块
---@param p player
function mForce:reg(p)
    if self:reged(p) then return end
    local list = self.regList
    table_insert( list, p )
    list[ p ] = true
end

---@private 玩家是否注册过
---@param p player
---@return bool
function mForce:reged(p)
    if self.regList[ p ] then
        return true
    end
    return false
end



---@ 新建空玩家组
---@return force
function mForce:new()
    ---@class force : cForce
    local g = {
        type = 'force',

    }
    setmetatable( g, cForce )

    g:init()

    return g
end

---@private 枚举所有玩家
---@param callback fun( p:player ):bool 返回true 表示退出枚举
function mForce:enum( callback )
    local list = self.regList
    local i = 1
    local p = list[i]

    --暴力枚举直至nil
    while p do

        if callback( p ) then
            return
        end

        i = i + 1
        p = list[i]
    end

end

---@private 初始化玩家组
function cForce:init()
    ---@type player[] 玩家组中所有玩家
    self.players = {}

end

--- 玩家组添加玩家
---@param p player
function cForce:addPlayer( p )
    if self:playerExist(p) then
        return  --玩家已存在玩家组
    end
    table_insert( self.players, p )
    self.players [ p ] = true
end

--- 判断玩家是否在玩家组中
---@param p player
---@return bool
function cForce:playerExist( p )
    if self.players [ p ] then
        return true
    end
    return false
end

--- 从玩家组中移除玩家
---@param p player
---@return bool
function cForce:removePlayer( p )
    if not self:playerExist( p ) then
        return false --找不到该玩家
    end
    local  list  =  self.players
    list[p] = nil
    for index, obj in ipairs(list) do
        if obj == p then
            table.remove( list, index )
            list[0] = list[0] - 1
            return true
        end
    end
    return true
end

---@private 枚举玩家组玩家
---@param callback fun( p:player ):bool 返回true 表示退出枚举
function cForce:enum( callback )
    local list = self.players
    local i = 1
    local p = list[i]

    --暴力枚举直至nil
    while p do

        if callback( p ) then
            return
        end

        --被删除则不增加索引值
        if p == list[i] then
            i = i + 1
        end

        p = list[i]
    end

end

---摧毁玩家组
function cForce:del()
    self.players = nil
    setmetatable(self,nil)
end


onReg()
return mForce